<template>
  <div style="display: flex;">
    <el-button type="primary" v-per2="['depart-list','post']" @click="doAdd">添加部门</el-button>
    <el-input  style="width: 200px;margin-left:20px;" v-model="search" placeholder="输入关键字搜索" clearable>
      <template #prepend>
        <el-button icon="Search" />
      </template>
    </el-input>
  </div>

  <el-row style="margin-top:20px;">

    <el-table
        :data="filterTableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="title" label="部门名称"/>
      <el-table-column prop="level" label="部门级别"/>
      <el-table-column
          v-if="hasButton([{'name':'depart-detail','method':'delete'},{'name':'depart-detail','method':'put'}])"
          prop="title" label="操作">
        <template #default="scope">
          <el-popconfirm
              cancel-button-type="danger"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmDelete(scope.row)"
              title="确认删除吗?">
            <template #reference>
              <el-button v-per2="['depart-detail','delete']" type="danger" size="small" icon="Delete"
                         class="card-small-btn"></el-button>
            </template>
          </el-popconfirm>
          <el-button v-per2="['depart-detail','put']" type="success" size="small" icon="Edit" class="card-small-btn"
                     @click="doEdit(scope.row,scope.$index)"></el-button>
          <el-button v-per2="['depart-detail','put']" type="primary" size="small" icon="Plus" class="card-small-btn"
                     @click="doAddByParent(scope.row,scope.$index)"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
  <MineDialog :obj="state.addDialog"></MineDialog>
  <MineDialog :obj="state.editDialog"></MineDialog>
</template>

<script setup>

import {computed, onMounted, reactive, ref} from "vue";
import {hasButton, hasPermission2} from "@/stores/permission.js";
import MineDialog from "@/components/DialogDouble.vue";
import {clearFormError, validateFormError} from "@/plugin/form.js";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus";

const search = ref('')
const searchFormRef = ref(null)
const state = reactive({
  isLoading: false,
  tableData: [],
  editId: -1,
  editIndex: -1,
  addDialog: {
    visible: false,
    title: "添加部门",
    data: [],
    form: {
      id: "",
      title: ""
    },
    errors: {
      title: "",
      id: ""
    },
    fields: [
      {name: 'id', label: '父级部门', wiget: 'tree_select'},
      {name: 'title', label: '部门名称', wiget: 'input'},
    ],
    doSubmit: doSubmit
  },
  editDialog: {
    visible: false,
    title: "编辑部门",
    form: {
      title: ""
    },
    errors: {
      title: "",
    },
    fields: [
      {name: 'title', label: '部门名称', wiget: 'input'},
    ],
    doSubmit: doSubmit
  },
  searchForm: {
    depart: ""
  }
})

onMounted(() => {
   initTableData()
})


function handleTreeData(treeData, searchValue) {
  if (!treeData || treeData.length === 0) {
    return [];
  }
  const array = [];
  for (let i = 0; i < treeData.length; i += 1) {
    if (handleTreeData(treeData[i].children, searchValue).length > 0 || treeData[i].title.includes(searchValue)) {
      array.push({
        ...treeData[i],
        children: handleTreeData(treeData[i].children, searchValue),
      });
    }
  }
  return array;
}

const filterTableData = computed(() => {
      let searchValue = search.value
      if (searchValue) {
        let treeData = state.tableData
        let handleTreeValue = handleTreeData(treeData, searchValue)
        return handleTreeValue
      }
      return state.tableData
    }
)

function initTableData() {
  if (!hasPermission2("depart-list", "get")) {
    return
  }
  state.isLoading = true
  _axios.get("/api/web/depart/").then((res) => {
    if (res.data.code === 0) {
      state.tableData = res.data.data;
      state.isLoading = false
    }
  })
}


function doAdd() {
  state.addDialog.visible = true
  state.addDialog.data = state.tableData
  state.editId = -1
  state.editIndex = -1
  clearFormError(state.addDialog.errors)
  state.addDialog.form = {}
}
function doAddByParent(row,idx){
  state.addDialog.visible = true
  state.addDialog.data = state.tableData
  state.editId = -1
  state.editIndex = -1
  clearFormError(state.addDialog.errors)
  state.addDialog.form = {
    id: row.id
  }

}
function doEdit(row,idx) {
  clearFormError(state.editDialog.errors)
  state.editDialog.visible = true
  state.editDialog.title = '编辑部门'
  state.editId = row.id
  state.editIndex = idx
  state.editDialog.form = {
    title:row.title
  }

}

function confirmDelete(row) {
  _axios.delete(`/api/web/depart/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      // state.tableData = state.tableData.filter((item) => {
      //   return row.id !== item.id
      // })
      if (res.data.data){
        ElMessage.error(res.data.data)
      }else{
        initTableData()
        ElMessage.success("删除成功")
      }

    } else {
      ElMessage.error("删除失败")
    }
  })
}


function doSubmit() {
  if (state.editId > 0) {
    _axios.put(`/api/web/depart/${state.editId}/`, state.editDialog.form).then((res) => {
      if (res.data.code === 0) {
        initTableData()
        state.editId = -1
        state.editIndex = -1
        state.editDialog.visible = false
      } else if (res.data.code === 2001) {
        validateFormError(state.editDialog.errors, res.data.detail)
      } else {
        ElMessage.error("编辑失败")
      }
    })
  } else {
    _axios.post('/api/web/depart/', state.addDialog.form).then((res) => {
      if (res.data.code === 0) {
        state.addDialog.visible = false
        initTableData()
      } else if (res.data.code === 2001) {
        validateFormError(state.addDialog.errors, res.data.detail)
      } else {
        ElMessage.error("添加失败")
      }
    })
  }
}

function doSearch() {
  initTableData()
}

function doResetSearchForm() {
  console.log(searchFormRef)
  searchFormRef.value.resetFields()
}

function confirmUserDelete() {

}

</script>

<style scoped>

</style>